package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

/**
 * @author ghy
 * @version v1.0
 * create on 2022/11/20 9:06
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.path}")
    private String path;

    /**
     * 文件回显
     * @param response
     * @param name
     * @throws Exception
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, String name) throws Exception {
        //1.定位原始文件
        File file = new File(path, name);
        //2.构建文件输入流
        FileInputStream in = new FileInputStream(file);
        //3.获取输出流
        ServletOutputStream out = response.getOutputStream();
        //表示写的是一个图片
        response.setContentType("image/jpeg");
        //4.读写操作
        int len;
        byte[] buffer = new byte[1024];
        while( (len = in.read(buffer)) != -1){
            out.write(buffer, 0, len);
            out.flush();
        }
        in.close();
    }

    /**
     * 文件上传
     * @param file
     * @return R<文件名>
     * @throws Exception
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        log.warn("upload:{}", file);

        //上传文件

        //1.获取到原始文件名
        String filename = file.getOriginalFilename();   //oiwefsda-bfsdkfh.jpg

        //2.重构文件名，文件名要唯一
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String suffixName = filename.substring(filename.lastIndexOf("."));   //.jpg
        filename = uuid + suffixName;

        //3.存储文件的路径   D:\imgs\oifibsdkfd.jpg
        File dest = new File(path, filename);
        if(!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        //4.上传
        file.transferTo(dest);

        //5.响应
        return R.success(filename);
    }

}
